<?php
namespace Com\Pay;
class WeiPaiPay{

    private $config = array();


    public function __construct($send_data){
        $this->config = $send_data;
    }

    /*生成支付连接*/
    public function getUrl($order_info){
        $price = $order_info['paymoney'];
        $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/Api/NotifyCallback/WeipaiNotify';
        $order_sn = $order_info['ordernumber'];
        $post_data = array(
            "version"  =>  $order_sn,
            'format' => 'json',
            'body' => 'CBpay',
            'total_fee' => $price,
            'app_id' => $this->config["mch_id"],
            'out_trade_no' => $order_sn,
            'callback_url' => $notifyUrl
        );

        $ContentSign = $this->setParam($post_data,$this->config['mch_key'],false); // 计算出Sign
        $post_data['sign'] = $ContentSign; // Sign签名
        $tar_url = "http://jspay.wiipay.cn/1/jspay/" . $order_info["payType"]["url"];
        $res = json_decode($this->send_post($tar_url,$post_data) , true);
        if($res['resultCode'] == "success"){
            return $res['url'];
        }
        return '';
    }

    private function setParam($param,$key,$IS_Notify){
        unset($param['PHPSESSID']);
        ksort($param);
        $str = "";
        foreach ($param as $k => $v){
            if($IS_Notify && $k == 'sign') continue;
            $str.= $k . '=' . $v . '&';
        }
        $str1 = rtrim($str , '&');
        $sign = strtoupper(md5($str1  . $key));
        return $sign;
    }

    //回调方法，把返回数据处理成统一规定返回
    public function response(){
        $data = $_REQUEST;
        $MySign = $this->setParam($data,$this->config['mch_key'],true);
        if($data['sign'] == $MySign){
            if($data['status'] == 'success'){
                return true;
            }else{
                // 失败
                return false;
            }
        }else{
            // 失败
            return false;
        }
    }


   private function send_post($url, $post_data) {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

}
